local __addon, __private = ...;
local YNLO = {}
local MT = __private.MT;
--local CT = __private.CT;
local VT = __private.VT;
local DT = __private.DT;
local DataAgent = DT.DataAgent;
local GetItemInfo = C_Item.GetItemInfo
--赋值
__private.YNLO = YNLO



--装备对应的词缀
local Suffixes = {
    ["敏捷之"] = "of Agility",
    [2] = "of Arcane Resistance",
    [3] = "of Arcane Wrath",
    [4] = "of Beast Slaying",
    [5] = "of Blocking",
    [6] = "of Concentration",
    [7] = "of Critical Strike",
    [8] = "of Defense",
    [9] = "of Eluding",
    [10] = "of Fiery Wrath",
    [11] = "of Fire Resistance",
    [12] = "of Frost Resistance",
    [13] = "of Frozen Wrath",
    [14] = "of Healing",
    [15] = "of Holy Wrath",
    [16] = "of Intellect",
    [17] = "of Marksmanship",
    [18] = "of Nature Resistance",
    [19] = "of Nature's Wrath",
    [20] = "of Power",
    [21] = "of Proficiency",
    [22] = "of Quality",
    [23] = "of Regeneration",
    [24] = "of Restoration",
    [25] = "of Retaliation",
    [26] = "of Shadow Resistance",
    [27] = "of Shadow Wrath",
    [28] = "of Sorcery",
    [29] = "of Spirit",
    [30] = "of Stamina",
    [31] = "of Strength",
    [32] = "of Striking",
    [33] = "of Toughness",
    [34] = "of Twain",
    [35] = "of the Bear",
    [36] = "of the Boar",
    [37] = "of the Eagle",
    [38] = "of the Falcon",
    [39] = "of the Gorilla",
    [40] = "of the Monkey",
    [41] = "of the Owl",
    [42] = "of the Tiger",
    [43] = "of the Whale",
    [44] = "of the Wolf",
}



YNLO.GetItemInfoByCid = function(cid)
    if not cid then
        return nil
    end
    local result = YNLO.ItemInfos[cid]
    if result then
        return result
    end
    result = { GetItemInfo(cid) }
    if #result > 0 then
        YNLO.ItemInfos[cid] = result
    else
        result = nil
    end
    return result
end

--添加控件
local function CreateDropdown(parentFrame, options, x, y, width, height, title, func)
    -- 创建下拉菜单框架
    local dropdown = CreateFrame("Button", "MyDropdown", parentFrame, "UIDropDownMenuTemplate")
    dropdown:SetPoint("TOPLEFT", parentFrame, "TOPLEFT", x, y)
    if width then
        UIDropDownMenu_SetWidth(dropdown, width)
    end
    -- if height then
    --     UIDropDownMenu_SetHeight(dropdown, height)

    -- end
    dropdown.options = options
    -- 初始化下拉菜单
    local function InitializeDropDown(self)
        for _, option in ipairs(options) do
            local info = UIDropDownMenu_CreateInfo()
            info.text = option.text
            info.value = option.value
            info.func = function(self)
                UIDropDownMenu_SetSelectedValue(dropdown, self.value)
                dropdown.optionValue = self.value
                if title then
                    UIDropDownMenu_SetText(dropdown, title .. ":" .. self:GetText())
                end
                if func then
                    func(parentFrame, self.value)
                end
            end
            UIDropDownMenu_AddButton(info)
        end
    end
    -- 设置下拉菜单的位置和初始值
    UIDropDownMenu_Initialize(dropdown, InitializeDropDown)
    if options and #options[1] then
        UIDropDownMenu_SetSelectedValue(dropdown, options[1].value)
        dropdown.optionValue = options[1].value
        if title then
            UIDropDownMenu_SetText(dropdown, title .. ":" .. options[1].text)
        end
    end
    return dropdown
end

YNLO.addProfitFrameControls = function(ProfitFrame, Frame)
    -- 添加数据源下拉框
    local options = {
        { text = "制作表", value = 1 },
        { text = "拍卖行", value = 2 }
    }
    ProfitFrame.DataList = CreateDropdown(ProfitFrame, options, -20, 25, 125, 30, "数据源")
    -- 添加利润列表
    local options = {
        { text = "成本", value = 0 },
        { text = "拍卖", value = 1 },
        { text = "丢店", value = 2 },
        { text = "分解", value = 3 },
        { text = "探矿", value = 4 },
        { text = "研磨", value = 5 }
    }
    ProfitFrame.ProfitOption = CreateDropdown(ProfitFrame, options, 120, 25, 60, 30, nil, Frame.F_Update)
    -- 添加排序依据
    local options = {
        { text = "值", value = 1 },
        { text = "率", value = 2 },
    }
    ProfitFrame.Orderby = CreateDropdown(ProfitFrame, options, 195, 25, 45, 30, nil, Frame.F_Update)
    -- 定义排序按钮
    local sortButton = CreateFrame("Button", "SortButton", ProfitFrame, "UIPanelButtonTemplate")
    sortButton:SetPoint("TOPLEFT", ProfitFrame, "TOPRIGHT", -80, 0) -- 调整位置
    sortButton:SetText("降序")
    sortButton:SetSize(50, 25)
    -- 定义排序
    Frame.isAscending = true
    -- 绑定按钮点击事件
    sortButton:SetScript("OnClick", function()
        Frame.isAscending = not Frame.isAscending
        if Frame.isAscending then
            sortButton:SetText("降序")
        else
            sortButton:SetText("升序")
        end
        Frame.F_Update()
    end)
end

-- 获取物品的价格
YNLO.GetVenderPriceByCid = function(cid)
    local iteminfo = YNLO.GetItemInfoByCid(cid)
    if iteminfo then
        return iteminfo[11]
    end
end
YNLO.GetVenderPriceBySid = function(sid)
    local info = DataAgent.get_info_by_sid(sid);
    local cid = info[5];
    if cid then
        return YNLO.GetVenderPriceByCid(cid)
    end
end


-- 打印表
YNLO.PrintTable = function(tbl, indent)
    if not indent then indent = 0 end
    for k, v in pairs(tbl) do
        local formatting = string.rep("  ", indent) .. k .. ": "
        if type(v) == "table" then
            print(formatting)
            YNLO.PrintTable(v, indent + 1)
        else
            print(formatting .. tostring(v))
        end
    end
end

-- 获取分解材料的总价格
local function GetDischantPriceByCid(cid)
    if YNLO.AT then -- 如果Auctionator存在
        local itemInfo = cid and YNLO.GetItemInfoByCid(cid)
        if itemInfo and itemInfo[2] then
            return YNLO.AT.Enchant.GetDisenchantAuctionPrice(itemInfo[2], itemInfo)
        end
    else
        print("YNLO.AT is nil")
    end
end

-- -- 定义 split 函数
-- local function split(inputstr, sep)
--     if sep == nil then sep = "%s" end
--     local t = {}
--     for str in string.gmatch(inputstr, "([^" .. sep .. "]+)") do
--         table.insert(t, str)
--     end
--     return t
-- end

local function round(number, decimals)
    decimals = decimals or 0
    local multiplier = 10 ^ decimals
    local integerPart, fractionalPart = math.modf(number * multiplier)
    if fractionalPart >= 0.5 then
        integerPart = integerPart + 1
    end
    return integerPart / multiplier
end


---------------------- 转抄自auctionator
local function Atr_GetDEitemName(itemID)
    local itemName = C_Item.GetItemInfo(itemID)
    return itemName or YNLO.AT.Constants.DisenchantingItemName[itemID]
end


local function ItemLevelMatches(entry, itemLevel)
    return itemLevel >= entry[YNLO.AT.Constants.DisenchantingProbabilityKeys.LOW] and
        itemLevel <= entry[YNLO.AT.Constants.DisenchantingProbabilityKeys.HIGH]
end

local function Atr_FindDEentry(classID, itemRarity, itemLevel)
    local itemClassTable = YNLO.AT.Constants.DisenchantingProbability[classID]
    local entries = (itemClassTable and itemClassTable[itemRarity]) or {}

    for index, entry in pairs(entries) do
        if ItemLevelMatches(entry, itemLevel) then
            return entry
        end
    end
end

local function GetDisenchantBreakdown(itemLink, itemInfo)
    local entry = Atr_FindDEentry(itemInfo[12], itemInfo[3], (C_Item.GetDetailedItemLevelInfo(itemLink)))
    local results = {}
    if entry then
        for x = 3, #entry, 3 do
            local percent = math.floor(entry[x] * 100) / 100
            local deitem = Atr_GetDEitemName(entry[x + 2])
            if (percent > 0) then
                --获取物品AH单价
                local price = YNLO.AT.API.v1.GetAuctionPriceByItemID("YNLO", entry[x + 2])
                local result = { entry[x + 2], deitem, entry[x + 1], percent, price }
                table.insert(results, result)
            end
        end
    end
    return results
end
----------------------


-- 获取分解材料的信息
local function GetDischantInfoByCid(cid)
    if YNLO.AT then -- 如果Auctionator存在
        local itemInfo = cid and { GetItemInfo(cid) }
        if itemInfo and itemInfo[2] then
            local results = GetDisenchantBreakdown(itemInfo[2], itemInfo)
            if results then
                results.price = YNLO.AT.Enchant.GetDisenchantAuctionPrice(itemInfo[2], itemInfo)
            end
            return results --itemid,itemName,num,precent,price
        end
    else
        print("YNLO.AT is nil")
    end
end


--利润列表显示
YNLO.showProfitList = function(Frame, list)
    local sid_list = Frame.list;
    wipe(list);
    if VT.AuctionMod == nil then
        return list
    end
    if Frame.ProfitFrame.DataList.optionValue == 1 then
        local pid = Frame.flag or DataAgent.get_pid_by_pname(Frame.F_GetSkillName());
        local profitRate = nil
        if Frame.ProfitFrame.ProfitOption.optionValue == 0 then --成本
            for index = 1, #sid_list do
                local sid = sid_list[index];
                local _, price_a_material = MT.GetPriceInfoBySID(
                    VT.SET[pid].phase, sid, DataAgent.get_num_made_by_sid(sid), nil);
                if price_a_material then
                    list[#list + 1] = { sid, price_a_material, 0 };
                end
            end
        elseif Frame.ProfitFrame.ProfitOption.optionValue == 1 then --拍卖
            for index = 1, #sid_list do
                local sid = sid_list[index];
                local price_a_product, price_a_material = MT.GetPriceInfoBySID(
                    VT.SET[pid].phase, sid, DataAgent.get_num_made_by_sid(sid), nil);
                if price_a_product and price_a_material and (price_a_product * 0.95 > price_a_material + 1) then
                    profitRate = (price_a_product * 0.95 - price_a_material) / price_a_material
                    profitRate = round(profitRate, 2)
                    list[#list + 1] = { sid, (price_a_product * 0.95 - price_a_material), profitRate };
                end
            end
        elseif Frame.ProfitFrame.ProfitOption.optionValue == 2 then --price, cost, cost_known, missing, cid, vendorPrice;丢店
            for index = 1, #sid_list do
                local sid = sid_list[index];
                local _, price_a_material = MT.GetPriceInfoBySID(
                    VT.SET[pid].phase, sid, DataAgent.get_num_made_by_sid(sid), nil);
                if price_a_material then
                    -- 获取丢店的价格
                    local vendorPrice = YNLO.GetVenderPriceBySid(sid)
                    if vendorPrice and vendorPrice - price_a_material > 0 then
                        profitRate = (vendorPrice - price_a_material) / price_a_material
                        profitRate = round(profitRate, 2)
                        list[#list + 1] = { sid, vendorPrice - price_a_material, profitRate };
                    end
                end
            end
        elseif Frame.ProfitFrame.ProfitOption.optionValue == 3 then --分解
            for index = 1, #sid_list do
                local sid = sid_list[index];
                local _, price_a_material, _, _, cid = MT.GetPriceInfoBySID(
                    VT.SET[pid].phase, sid, DataAgent.get_num_made_by_sid(sid), nil);
                if price_a_material and cid then
                    local dischantPrice = GetDischantPriceByCid(cid)
                    if dischantPrice and dischantPrice - price_a_material > 0 then
                        profitRate = (dischantPrice - price_a_material) / price_a_material
                        profitRate = round(profitRate, 2)
                        list[#list + 1] = { sid, dischantPrice - price_a_material, profitRate };
                    end
                end
            end
        end
    elseif Frame.ProfitFrame.DataList.optionValue == 2 then
        --拍卖数据，只能显示丢店，分解、探矿、研磨
        -- local dbKey = "gr:11984:of Concentration"
        -- local item = strsplit(dbKey, ":")
        -- --local temp = "|cff000000|Hitem:"..item[2].."|h[text]|h|r"
        -- print("|cff0070dd|Hitem:11984:::::::|h[灵猴手套]|h|r")
        -- local itemLink = /dump(|cff0070dd|Hitem:11984:::::::|h[灵猴手套]|h|r) "|cff0070dd|Hitem:11984:::::::|h[灵猴手套]|h|r"


        for dbKey, value in pairs(YNLO.DataBase) do
            if Frame.ProfitFrame.ProfitOption.optionValue < 2 then --如果不是丢店以上，直接return
                return
            end
            local price = YNLO.AT.Database:GetPrice(tostring(dbKey))
            if price then
                local itemTable = { strsplit(":", dbKey) }
                --装备：id:后缀
                local itemID = itemTable[1]
                if itemTable[2] then --这里如果是装备，则要返回装备的itemlink
                    itemID = itemTable[2]
                end
                --获取到物品ID
                local itemInfo = YNLO.GetItemInfoByCid(itemID)
                if itemInfo then
                    local itemName, texture, vendorPrice = itemInfo[1], itemInfo[10], itemInfo[11]
                    if itemTable[3] then --还原itemName
                        itemName = itemName .. " " .. itemTable[3]
                    end
                    if Frame.ProfitFrame.ProfitOption.optionValue == 2 then --丢店
                        --获取丢店利润
                        if vendorPrice and (vendorPrice - price) > 0 then
                            local profitRate = (vendorPrice - price) / price
                            profitRate = round(profitRate, 2)
                            list[#list + 1] = { itemID, vendorPrice - price, profitRate, { itemName, texture } };
                        end
                    elseif Frame.ProfitFrame.ProfitOption.optionValue == 3 then --分解
                        local dischantPrice = GetDischantPriceByCid(itemID)
                        if dischantPrice and (dischantPrice - price) > 0 then
                            local profitRate = (dischantPrice - price) / price
                            list[#list + 1] = { itemID, dischantPrice - price, profitRate, { itemName, texture } };
                        end
                    end
                end
            end
        end
    end
    -- 排序
    if Frame.isAscending then
        table.sort(list, function(v1, v2)
            if Frame.ProfitFrame.Orderby.optionValue == 1 then
                return v1[2] > v2[2];
            else
                return v1[3] > v2[3];
            end
        end);
    else
        table.sort(list, function(v1, v2)
            if Frame.ProfitFrame.Orderby.optionValue == 1 then
                return v1[2] < v2[2];
            else
                return v1[3] < v2[3];
            end
        end);
    end
end

--重设按钮
YNLO.SetButton = function(Button, val, LT_SharedMethod)
    if Button.Frame.flag == "explorer" then
        if Button.Frame.ProfitFrame.DataList.optionValue == 2 then
            --传入的val[1]是物品的ID,val[4]是物品的itemInfoand Button.Frame:GetName() == "ALA_TRADESKILL_EXPLORER"
            if val[4] then
                --print(val[4][1], val[4][2], val[4][3])
                -- if val[4][3] ~= nil then
                --     local r, g, b = C_Item.GetItemQualityColor(val[4][3]);
                --     Button.QualityGlow:SetVertexColor(r, g, b);
                --     Button.QualityGlow:Show();
                -- else
                --     Button.QualityGlow:Hide();
                -- end
                Button.QualityGlow:Hide();
                Button:SetScript("OnEnter", nil);
                Button:SetScript("OnLeave", nil);
                Button:SetScript("OnClick", nil);
                Button.Icon:SetTexture(val[4][2]);
                --Button.Icon:SetVertexColor(1.0, 0.0, 0.0, 1.0);
                Button.Title:SetText(val[4][1]);
                Button:Show();
            end
        end
        --设置提示
        local note = MT.GetMoneyString(val[2])
        if val[3] then
            note = note .. " " .. val[3]
        end
        Button.Note:SetText(note);
        -- if Button.prev_sid ~= val[1] then
        --     VT.__menulib.ShowMenu(Button);
        --     Button.prev_sid = val[1];
        -- end
        -- Button.val = val;
    else
        Button:SetScript("OnEnter", LT_SharedMethod.SkillListButton_OnEnter);
        Button:SetScript("OnLeave", LT_SharedMethod.SkillListButton_OnLeave);
        Button:SetScript("OnClick", LT_SharedMethod.SkillListButton_OnClick);
    end
end


--根据cid添加tooltip的分解信息/dump GetItemIcon(23787)
YNLO.addDischantLinesByCid = function(lines, cid)
    --添加卖店信息
    local vendorPrice = YNLO.GetVenderPriceByCid(cid)
    if vendorPrice then
        lines[#lines + 1] = "|cffff7f00卖店:|r";
        lines[#lines + 1] = "|cffff7f00单价|r" .. MT.GetMoneyString(vendorPrice)
    end
    local dischantInfo = GetDischantInfoByCid(cid)
    if dischantInfo and dischantInfo.price then
        lines[#lines + 1] = "|cffff7f00分解:|r";
        if dischantInfo.price == 0 then
            dischantInfo.price = "|cffff0000未知|r"
        else
            dischantInfo.price = MT.GetMoneyString(dischantInfo.price)
        end
        lines[#lines + 1] = "|cffff7f00总价|r" .. dischantInfo.price
        for _, value in pairs(dischantInfo) do --itemid,itemName,num,precent,price
            if value[1] then
                lines[#lines + 1] = "  " .. value[2] .. "x" .. value[3] .. "(" .. value[4] .. "%)";
                if value[5] then
                    value[5] = MT.GetMoneyString(value[5] * value[3])
                else
                    value[5] = "|cffff0000未知|r"
                end
                lines[#lines + 1] = value[5];
            end
        end
    end
end


--注册事件
local frame = CreateFrame("Frame")

-- 事件处理函数
local function OnEvent(self, event, addonName)
    if event == "ADDON_LOADED" then
        if addonName == "Auctionator" then
            -- 目标插件已加载
            print("YNLO拍卖数据加载成功...")
            YNLO.AT = Auctionator
            YNLO.realmInfo = GetRealmName() .. " " .. (UnitFactionGroup("player"))
            YNLO.DataBase = AUCTIONATOR_PRICE_DATABASE[YNLO.realmInfo]
        elseif addonName == __addon then
            if not alaTradeSkillSV.ItemInfos then
                alaTradeSkillSV.ItemInfos = {}
            end
            YNLO.ItemInfos = alaTradeSkillSV.ItemInfos
        end
        if YNLO.AT and YNLO.ItemInfos then
            self:UnregisterEvent("ADDON_LOADED") -- 取消事件注册，避免重复执行
        end
    end
end

-- 注册事件
frame:RegisterEvent("ADDON_LOADED")
frame:SetScript("OnEvent", OnEvent)
